package com.wanhelibs.custom_view.views;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.orhanobut.logger.Logger;
import com.wanhe.base.Const;
import com.wanhe.base.model.disgn.DSFile;
import com.wanhe.base.model.disgn.Event;
import com.wanhe.base.model.disgn.PageViewModel;
import com.wanhe.base.model.disgn.ViewEvent;
import com.wanhe.base.model.disgn.ViewItem;
import com.wanhe.base.model.holder.CustomPageHolder;
import com.wanhe.base.model.holder.FileHolder;
import com.wanhe.base.util.ObjectUtil;
import com.wanhe.mealbookmodule.adapter.MealBookItemsAdapter;
import com.wanhe.viewconf.views.child.MealBookChildItemView;
import com.wanhe.viewconf.views.child.interfaces.IBindingViewFunc;
import com.wanhe.viewconf.views.child.interfaces.IViewReady;
import com.wanhe.viewconf.views.group.CoordinateViewGroup;
import com.wanhelibs.R;
import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutionException;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * File Name:MealBookPopupView.java<br/>
 * Package Name:com.wanhelibs.custom_view.views<br/>
 * Date:2017/7/13 19:26<br/>
 * author:chendeji<br/>
 * desc: 弹窗控件<br/>
 * Copyright (c) 2017/7/13, 781571323@qq.com All Rights Reserved.
 */
public class MealBookPopupView extends MealBookChildItemView
		implements
			IBindingViewFunc ,
			IViewReady {

	private ImageView			popBkg;
	private CoordinateViewGroup	popViewgourp;
	private PageViewModel		mPageViewModel;

	public MealBookPopupView(Context context) {
		super(context);
		initView(context);
	}

	private void initView(Context context) {
		LayoutInflater.from(context).inflate(R.layout.popup_page_layout, this, true);
		popBkg = (ImageView) findViewById(R.id.iv_pop_bkg);
		popViewgourp = (CoordinateViewGroup) findViewById(R.id.cvg_pop_view_holder);
		popViewgourp.setListener(new CoordinateViewGroup.OnRequireDismissListener() {
			@Override
			public void onCancleRequire() {
				/**
				 * 执行隐藏的操作
				 * 
				 * @author 陈德基
				 * @time 2017/8/1 11:12
				 */
				hide(null, null);

				/**
				 * 将本地的事件发送出去
				 * 
				 * @author 陈德基
				 * @time 2017/7/15 11:52
				 */
				List <Event> events = MealBookPopupView.this.mItem.getEvents();
				if (ObjectUtil.checkObjectList(events)) {
					sendEvents(events);
				}
			}
		});
	}

	@Override
	public void bind(Event event, ViewEvent.Coor coor) {
		if (ObjectUtil.checkObject(event)) {
			String ctype = event.getCtype();
			if (!TextUtils.isEmpty(ctype)) {
				switch (ctype) {
					case ViewItem.VIEW_TYPE_ANIMATE :
						bindAnimateObj(event);
						break;
				}
			}
		}
	}

	@Override
	public void ready(Event event, ViewEvent.Coor coor) {
		sendEvent(event);
	}

	private class BitmapInfo {
		public String	url;
		public int		width;
		public int		height;
	}

	private void initImageView(PageViewModel pageViewModel) {
		this.mPageViewModel = pageViewModel;
		int fid = pageViewModel.getImage();
		DSFile file = FileHolder.getInstance().get(fid);
		if (!ObjectUtil.checkObject(file)) {
			Logger.t(TAG).e("加载背景图片失败，文件找不到  %d", pageViewModel.getImage());
			return;
		}
		String fileName = file.getFileName();
		final String url = Const.getUrl(fileName, Const.imageBaseUrl);
		Observable.create(new ObservableOnSubscribe <BitmapInfo>() {
			@Override
			public void subscribe(@NonNull ObservableEmitter <BitmapInfo> e) throws Exception {
				FutureTarget <
						File> future = Glide.with(getContext()).load(url).downloadOnly(30, 30);
				try {
					File cacheFile = future.get();
					String path = cacheFile.getAbsolutePath();
					BitmapFactory.Options options = new BitmapFactory.Options();
					// 设置为true,表示解析Bitmap对象，该对象不占内存
					options.inJustDecodeBounds = true;
					BitmapFactory.decodeFile(path, options);
					int bitmapWidth = options.outWidth;
					int bitmapHeight = options.outHeight;
					if (bitmapWidth <= 1540 && bitmapHeight <= 2050) {
						BitmapInfo info = new BitmapInfo();
						info.url = url;
						info.width = bitmapWidth;
						info.height = bitmapHeight;
						e.onNext(info);
					} else {
						e.onError(new Throwable("图片太大"));
					}
				} catch (InterruptedException err) {
					err.printStackTrace();
				} catch (ExecutionException err) {
					err.printStackTrace();
				}
			}
		}).subscribeOn(Schedulers.io()) // 指定 subscribe() 发生在 IO 线程
				.observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber
				// 的回调发生在主线程
				.subscribe(new Observer <BitmapInfo>() {
					@Override
					public void onSubscribe(@NonNull Disposable d) {

					}

					@Override
					public void onNext(@NonNull BitmapInfo bitmapInfo) {
						// Glide 框架加载图片
						Glide.with(getContext()).load(bitmapInfo.url)
								.error(com.wanhe.mealbookmodule.R.drawable.error_img)
								.diskCacheStrategy(DiskCacheStrategy.SOURCE).override(600, 960)
								.into(target);
					}

					@Override
					public void onError(@NonNull Throwable e) {
						Glide.with(getContext()).load(com.wanhe.mealbookmodule.R.drawable.error_img)
								.into(target);
					}

					@Override
					public void onComplete() {

					}
				});
	}

	private SimpleTarget target = new SimpleTarget <GlideBitmapDrawable>() {
		@Override
		public void onLoadStarted(Drawable placeholder) {
			// showProcess();
		}

		@Override
		public void onResourceReady(GlideBitmapDrawable drawable, GlideAnimation glideAnimation) {
			setItem(drawable);
		}

		@Override
		public void onLoadFailed(Exception e, Drawable errorDrawable) {
			setItem(errorDrawable);
		}
	};

	private void setItem(Drawable bg) {
		float width = bg.getIntrinsicWidth();
		float height = bg.getIntrinsicHeight();
		popBkg.setBackground(bg);
		popViewgourp.setRealScale(width / height);
		// hideProcess();
		// 在所有控件都添加都树结构中的时候在显示，一次性刷新，减少过度刷新
		initMealBookItems(this.mPageViewModel);
	}

	private void initMealBookItems(PageViewModel model) {

		MealBookItemsAdapter pagerAdapter = new MealBookItemsAdapter(getContext(),
				model.getItems());
		popViewgourp.setAdapter(pagerAdapter);
		popViewgourp.initMealBookPage();
	}

	@Override
	public void setViewStatu(int viewStatu) {
		if (getVisibility() == VISIBLE) {
			viewStatu = VIEW_DIRTY;
		}
		super.setViewStatu(viewStatu);
	}

	@Override
	public void show(final Event event, ViewEvent.Coor coor) {
		// super.show(event, coor);
		// showDetail(event);

		/**
		 * 如果有动画需要执行，执行动画
		 * 
		 * @author 陈德基
		 * @time 2017/8/3 14:36
		 */
		if (ObjectUtil.checkObject(animationIn)) {
			animationIn.setAnimationListener(new Animation.AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					showDetail(event);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}
			});
			animationIn.setDuration(this.getItem().getDurationIn());
			this.startAnimation(animationIn);
		} else {
			setVisibility(VISIBLE);
			showDetail(event);
		}
	}

	private void showDetail(Event event) {
		if (ObjectUtil.checkObject(event)) {
			if (ObjectUtil.checkObject(this.mItem)) {
				int page = this.mItem.getPage();
				CustomPageHolder instance = CustomPageHolder.getInstance();
				PageViewModel pageViewModel = instance.get(page);
				if (ObjectUtil.checkObject(pageViewModel)) {
					setViewStatu(VIEW_DIRTY);
					initImageView(pageViewModel);
				}
			}
		}
	}
}
